import { defineConfig } from "vite";
import { resolve } from "path";
import { createVitePlugins } from "./build/vite";
import type { ConfigEnv, UserConfig } from "vite";
import { loadEnv } from "vite";

// 当前执行node命令时文件夹的地址(工作目录)
const root = process.cwd();

// 路径查找
function pathResolve(dir: string) {
  return resolve(root, ".", dir);
}
export default ({ command, mode }: ConfigEnv): UserConfig => {
  let env = {} as any;
  const isBuild = command === "build";
  if (!isBuild) {
    env = loadEnv(
      process.argv[3] === "--mode" ? process.argv[4] : process.argv[3],
      root
    );
  } else {
    env = loadEnv(mode, root);
  }
  let isProd = mode == "prod";
  return {
    resolve: {
      extensions: [
        ".mjs",
        ".js",
        ".ts",
        ".jsx",
        ".tsx",
        ".json",
        ".scss",
        ".css",
        ".styl",
      ],
      alias: [
        // {
        //     find: 'vue-i18n',
        //     replacement: 'vue-i18n/dist/vue-i18n.cjs.js'
        // },
        {
          find: /\@\//,
          replacement: `${pathResolve("src")}/`,
        },
      ],
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/css/my_style.scss" as *; `, // 全局注入
          // additionalData: `@use "@/assets/css/my_style.scss" as *;@use "@/assets/css/element.scss" as *; `, // 全局注入
        },
      },
    },
    plugins: createVitePlugins(),
    server: {
      port: env.VITE_PORT || 8888,
      host: "0.0.0.0",
      // 本地跨域代理. 目前注释的原因：暂时没有用途，server 端已经支持跨域
      // proxy: {
      //   ['/admin-api']: {
      //     target: env.VITE_BASE_URL,
      //     ws: false,
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(new RegExp(`^/admin-api`), ''),
      //   },
      // },
    },
    build: {
      minify: "terser", // 使用 terser 压缩代码
      outDir: env.VITE_OUT_DIR || "dist",
      sourcemap: env.VITE_SOURCEMAP === "true" ? "inline" : false,
      terserOptions: {
        compress: {
          drop_console: isProd ? true : false, // 移除 console
          drop_debugger: isProd ? true : false, // 移除 debugger
        },
      },
      // rollupOptions: {
      //   output: {
      //     manualChunks: {
      //       echarts: ["echarts"], // 将 echarts 单独打包，参考 https://gitee.com/yudaocode/yudao-ui-admin-vue3/issues/IAB1SX 讨论
      //     },
      //   },
      // },
      // optimizeDeps: {include, exclude}
    },
  };
};
